<template>
    <div class="controller-config-list">
        <ControllerConfig :config="devConfig" @activate-status-change="onActiveStatusChange(i)"
            @copy-controller-config="onCopyControllerConfig(i, $event)"
            @update:config="updateDeviceConfig(i, devConfig)" v-for="devConfig, i in devConfigs" :key="devConfig.uuid">
        </ControllerConfig>
    </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, ref } from "vue"
import { getDeviceConfigs, saveDeviceConfigs } from "@/api"
import { DeviceFunctionalConfig } from "@/models"
import ControllerConfig from "./ControllerConfig.vue"
import { CallFrequencyLimiter } from "@/components/control_panel/widgets"
import { insertAfter } from "element-sci-ui"
import { ElNotification } from "element-plus"

const devConfigs = ref<DeviceFunctionalConfig[]>([])
// const activeIndices = ref<number[]>([]) // 激活的配置的索引，配置序号与devConfigs对应
onBeforeMount(async () => {
    devConfigs.value = await getDeviceConfigs()
})

const freqLimiter = new CallFrequencyLimiter((data) => {
    saveDeviceConfigs(data).then(() => {
        ElNotification.success({
            title: "保存成功",
            message: "配置已保存",
            duration: 1000
        })
    })
})
const updateDeviceConfig = (i: number, devConfig: DeviceFunctionalConfig) => {
    devConfigs.value[i] = devConfig
    freqLimiter.push_data(devConfigs.value)
}

const onCopyControllerConfig = (i: number, newData: DeviceFunctionalConfig) => {
    devConfigs.value = insertAfter(devConfigs.value, newData, i)
    freqLimiter.push_data(devConfigs.value)
}

const onActiveStatusChange = (i: number) => {
    const name = devConfigs.value[i].device_name
    for (let j = 0; j < devConfigs.value.length; j++) {
        if (devConfigs.value[j].device_name == name) {
            devConfigs.value[j].activated = false
        }
    }
    devConfigs.value[i].activated = true
    freqLimiter.push_data(devConfigs.value)
}
</script>
<style lang="css">
.controller-config-list {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    max-width: 100%;
    max-height: 100%;
}
</style>